package com.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.model.*;
import com.example.demo.service.CustomerService;
import com.example.demo.service.ManagerService;
import com.example.demo.service.ProductService;
import com.example.demo.service.impl.CustomerServiceimpl;
import com.example.demo.util.JsonResult;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HelloController extends BaseController{
    /*getMapping=URL+ method=get  即路径加get方法*/

    @Resource
    private ManagerService managerService;
    @Resource
    private CustomerService customerService;
    @Resource
    private ProductService productService;


    @GetMapping("/Appliances.html")
    public String Appliances(){
        return "Appliances";
    }

    @GetMapping("/updateproduct{pid}")
    public String updateproduct(@PathVariable("pid")Integer pid, Model model){
        Product product= productService.getById(pid);
        model.addAttribute("product",product);
        return "updateproduct";
    }

    @GetMapping("/userdata")
    public String userdata(){
        return "userdata";
    }


    @GetMapping("/myproduct")
    public String myproduct(){
        return "myproduct";
    }

    @GetMapping("/password")
    public String password(){
        return "password";
    }

    @GetMapping("/uploadproduct")
    public String uploadproduct(){
        return "uploadproduct";
    }

    @GetMapping("/payment")
    public String payment(){
        return "payment";
    }

    @GetMapping("/orderConfirm")
    public String orderConfirm(){return "orderConfirm";}

    @GetMapping("/cart")
    public String cart(){return "cart";}

    @RequestMapping("/")
    public String root(){
        return "redirect:/homepage";
    }

    @GetMapping("/homepage")
    public String homepage(){
        return "homepage";
    }

    @GetMapping("/Product")
    public String index(){
        return "Product";
    }

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/register")
    public String register(){
        return "register";
    }

    @GetMapping("/download")
    public String download(){
        return "download";
    }

    @GetMapping("/fileupload")
    public String fileupload(){
        return "fileupload";
    }


    /*重定向*//*
    @GetMapping("/download")
    public String redirect(){
        return "redirect:/login";
    }*/

   /* @GetMapping("/response")
    @ResponseBody
    public Person responsebody(){
        Person person=new Person("test","pass",9);
        return person;  //返回的是return里面的内容，为不是页面。
    }*/

    /*@GetMapping("/response")
    @ResponseBody
    public List responsebody(){
        Person person=new Person("test","pass",9);
        Person person1=new Person("test","pass",10);
        Person person2=new Person("test","pass",11);
        List list=new ArrayList();
        list.add(person);
        list.add(person1);
        list.add(person2);
        return list;  //返回的是return里面的内容，为不是页面。
    }
*/
   /* @PostMapping("/yy")
    public String submitLogin(String username,String password){
        System.out.println(username);
        System.out.println(password);
        return "homepage";
    }*/

    @GetMapping("/sumbit")
    @ResponseBody
    public Boolean Submit(){
        return true;
    }

    @PostMapping("/person")
    @ResponseBody
    public Person show(String name,String password){
        Person person=new Person(name,password);
        System.out.println(person.toString());
        return person;
    }


    @GetMapping("/mana")
    public  String manager(Model model){
        List<Manager> list=managerService.list(null);
        model.addAttribute("manaList",list);
        System.out.println(list.toString());
        return "manager";
    }

    @GetMapping("/editmanager")
    public  String editmanager(int id,Model model){

       Manager manager= managerService.getById(id);
       model.addAttribute("manager",manager);

       return "managerEdit";

    }

    @GetMapping("/deletemanager")
    public  String deletemanager(int id){
        managerService.removeById(id);
        return "redirect:/mana";
    }

    @PostMapping("/saveManager")
    public  String saveManager(int id,String username,String password,Model model){
        Manager manager=new Manager();
        manager.setId(id);
        manager.setUsername(username);
        manager.setPassword(password);
        managerService.updateById(manager);
        return "redirect:/mana";
    }

    @GetMapping("/addManager")
    public String addManager(){
        return "managerAdd";
    }

    @PostMapping("/saveAddManager")
    public  String saveAddManager(Manager manager){

        System.out.println();
        managerService.save(manager);
        return "redirect:/mana";
    }

    @GetMapping("/houtai")
    public String houtai(Model model){
//        model.addAttribute();
        return "houtai";
    }


/*分页*/
    @GetMapping("/page")
    @ResponseBody
    public Object getPage(QueryPage queryPage){
        System.out.println(queryPage.toString());
        Page page=new Page(queryPage.getCurPage(),queryPage.getPageSize());
        Page<Manager> page1=(Page<Manager>)managerService.page(page);
        return page1;
    }


    @GetMapping("/pageview")
    public ModelAndView getView(){
        return new ModelAndView("manage");
    }


    @PostMapping("/login")
    public String doLogin(String name, String password, HttpServletRequest request, HttpServletResponse response,Model model) throws NoSuchAlgorithmException {

            Customer customer = customerService.doLogin(name);
            Map<String,Object> errors=new HashMap<>();
            String url;
            System.out.println(MD5Utils.getMD5Str(password));
    if(customer!=null){
    if(customer.getPassword().equals(MD5Utils.getMD5Str(password))){
                    System.out.println("密码正确，登陆成功");

                    Cookie customerCookie=new Cookie("customercookie",name);
                    customerCookie.setMaxAge(604800);
                    customerCookie.setPath("/");
                    response.addCookie(customerCookie);
                    HttpSession session=request.getSession();
                    session.setAttribute("customer",customer);
                    session.setAttribute("uid", customer.getId());
                    System.out.println(session.getAttribute("uid").toString());
                    session.setAttribute("name", customer.getName());
                    session.setMaxInactiveInterval(604800);
                    url="homepage";
    }else{
                    model.addAttribute("errormsg","密码错误");
                    System.out.println("密码错误");
                    url="login";
                    errors.put("msg","密码错误");
    }
    }else{
                model.addAttribute("errormsg","用户名错误");
                System.out.println("⽤户不存在");
                url="login";
                errors.put("msg","⽤户不存在");
    }
            request.setAttribute("errors",errors);
    return url;
    }

    @PostMapping("/register")
    public String register(Customer customer){
        try {
            customer.setPassword(MD5Utils.getMD5Str(customer.getPassword()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        customerService.save(customer);
        return "redirect:/login";
    }


    //注销
    @GetMapping("/outLogin")
    public String outLogin(HttpSession session,HttpServletRequest request, HttpServletResponse response){
        //获取cookie
        Cookie[] cookies=request.getCookies();
        for(Cookie cookie: cookies){
            cookie.setMaxAge(0);
            cookie.setPath("/");  //路径一定要写上，不然销毁不了
            response.addCookie(cookie);
        }

        //通过session.invalidata()方法来注销当前的session
        session.invalidate();
        return "login";
    }

    //缓存
    @GetMapping("/testcache")
    @ResponseBody
    public Object testcache(){
        return customerService.getOneCustomer(1);
    }


    /**
     *
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @param session
     * @return
     * @throws CustomerServiceimpl.UserNotFoundException
     * @throws NoSuchAlgorithmException
     * @throws CustomerServiceimpl.PasswordNotMatchException
     * @throws CustomerServiceimpl.UpdateException
     */
    @PostMapping("change_password")
    @ResponseBody
    public JsonResult<Void> changePassword(String oldPassword, String newPassword, HttpSession session) throws CustomerServiceimpl.UserNotFoundException, NoSuchAlgorithmException, CustomerServiceimpl.PasswordNotMatchException, CustomerServiceimpl.UpdateException {
        Integer uid = getUidFromSession(session);
        customerService.changePassword(uid,oldPassword,newPassword);
        return new JsonResult<>(OK);
    }



}
